<template>
	<div>
		<!--  编辑弹框-->
		<el-dialog :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="35%">
			<template #header="{ titleId, titleClass }">
				<div class="my-header">
					<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
					<el-button type="danger" plain size="small" class="custom-close-btn" @click="handleSilentClose">
						<el-icon :size="16"><Close /></el-icon>
					</el-button>
				</div>
			</template>
			<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
				<el-form-item label="装备名称" prop="name">
					<el-input v-model="form.name" />
				</el-form-item>

				<el-form-item label="装备图片" prop="img">
					<UploadImage v-model="form.img" :file-size="5" :width="'150px'" :height="'150px'" :disabled="false" />
				</el-form-item>

				<el-form-item label="攻击力" prop="aggressivity">
					<el-input-number v-model="form.aggressivity" />
				</el-form-item>
				<el-form-item label="暴击率" prop="critical">
					<el-input-number v-model="form.critical" />
				</el-form-item>
				<el-form-item label="防御" prop="defense">
					<el-input-number v-model="form.defense" />
				</el-form-item>
				<el-form-item label="法力上限" prop="mana">
					<el-input-number v-model="form.mana" />
				</el-form-item>
				<el-form-item label="火焚耐性" prop="fire">
					<el-input-number v-model="form.fire" />
				</el-form-item>
				<el-form-item label="寒冻耐性" prop="ice">
					<el-input-number v-model="form.ice" />
				</el-form-item>
				<el-form-item label="毒伤耐性" prop="drug">
					<el-input-number v-model="form.drug" />
				</el-form-item>
				<el-form-item label="雷蛰耐性" prop="thunder">
					<el-input-number v-model="form.thunder" />
				</el-form-item>
				<el-form-item label="所属套装" prop="belongSuit">
					<el-select v-model="form.belongSuit" placeholder="选择所属套装" clearable filterable remote :remote-method="searchBelongSuits">
						<el-option v-for="item in belongSuitOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="所属类型" prop="belong">
					<el-select v-model="form.belong" placeholder="请选择所属类型" clearable>
						<el-option v-for="item in belongOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="handleSubmitForm(ruleFormRef)"> 提交 </el-button>
				</span>
			</template>
		</el-dialog>

		<el-row>
			<!--  分页查询表单按钮-->
			<el-col>
				<el-form :inline="true">
					<!--        查询输入框-->
					<el-row>
						<el-col>
							<el-form-item label-width="5px">
								<el-input v-model="name" placeholder="输入装备名称" />
							</el-form-item>
							<el-form-item label="所属套装">
								<el-select
									v-model="belongSuitFilter"
									placeholder="全部套装"
									clearable
									filterable
									remote
									:remote-method="searchBelongSuits"
									style="width: 150px"
								>
									<el-option v-for="item in belongSuitOptions" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="所属类型">
								<el-select v-model="belongFilter" placeholder="全部类型" clearable style="width: 100px">
									<el-option v-for="item in belongOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-form-item>
							<el-form-item label-width="5px">
								<el-button type="primary" :icon="Search" @click="load"> 查询 </el-button>
								<el-button type="warning" :icon="Refresh" @click="handleReset"> 重置 </el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-col>
			<!-- 新增和批量按钮 -->
			<el-col style="margin-bottom: 10px; display: flex; gap: 10px">
				<!--   新增   -->
				<div v-permission="'sys:equip:add'">
					<el-button type="primary" :icon="Plus" size="small" plain @click="handleAdd"> 新增 </el-button>
				</div>
				<!--   批量导入   -->
				<div v-permission="'sys:equip:batch:upload'">
					<el-upload action="" :before-upload="beforeBatchUpload" :show-file-list="true">
						<el-button type="success" :icon="Upload" size="small" plain> 批量导入 </el-button>
					</el-upload>
				</div>
				<!--   批量删除   -->
				<div v-permission="'sys:equip:batch:delete'">
					<el-popconfirm
						confirm-button-text="确定"
						cancel-button-text="取消"
						:icon="InfoFilled"
						icon-color="#626AEF"
						title="确认要批量删除吗？"
						@confirm="handleBatchDel"
						@cancel="load"
					>
						<template #reference>
							<el-button type="danger" :disabled="disabled" :icon="Delete" size="small" plain> 批量删除 </el-button>
						</template>
					</el-popconfirm>
				</div>

				<div v-permission="'sys:equip:batch:export'">
					<el-button type="warning" :icon="Download" :disabled="disabled" size="small" plain @click="handleBatchExport"> 批量导出 </el-button>
				</div>
			</el-col>
			<!--  表格页面-->
			<el-col>
				<el-table
					:data="tableData"
					style="width: 100%"
					:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column prop="id" label="ID" align="center" sortable />
					<el-table-column prop="name" label="装备名称" align="center" show-overflow-tooltip />
					<el-table-column prop="img" label="装备图片" align="center">
						<template #default="scope">
							<el-image
								style="width: 50px; height: 50px"
								:src="scope.row.img"
								:preview-src-list="[scope.row.img]"
								:zoom-rate="1.2"
								:max-scale="7"
								:preview-teleported="true"
								:min-scale="0.2"
								:initial-index="0"
								fit="contain"
							/>
						</template>
					</el-table-column>
					<el-table-column prop="aggressivity" label="攻击力" align="center" sortable />
					<el-table-column prop="critical" label="暴击率" align="center" sortable />
					<el-table-column prop="defense" label="防御" align="center" sortable />
					<el-table-column prop="mana" label="法力上限" align="center" sortable />
					<el-table-column prop="fire" label="火焚耐性" align="center" sortable />
					<el-table-column prop="ice" label="寒冻耐性" align="center" sortable />
					<el-table-column prop="drug" label="毒伤耐性" align="center" sortable />
					<el-table-column prop="thunder" label="雷蛰耐性" align="center" sortable />
					<el-table-column prop="belongSuit" label="所属套装" align="center">
						<template #default="scope">
							{{ getSuitName(scope.row.belongSuit) }}
						</template>
					</el-table-column>
					<el-table-column prop="belong" label="所属类型" align="center">
						<template #default="scope">
							{{ getBelongLabel(scope.row.belong) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="240">
						<template #default="scope">
							<div style="display: flex; justify-content: center; gap: 10px">
								<div>
									<el-button v-permission="'sys:equip:update'" type="warning" :icon="Refresh" size="small" @click="handleUpdate1(scope.row.id)">
										个性属性
									</el-button>
								</div>
								<div>
									<el-button v-permission="'sys:equip:update'" type="primary" :icon="Edit" size="small" @click="handleUpdate(scope.row.id)">
										编辑
									</el-button>
								</div>
								<div v-permission="'sys:equip:delete'">
									<el-popconfirm
										confirm-button-text="确定"
										cancel-button-text="取消"
										:icon="InfoFilled"
										icon-color="#626AEF"
										title="确认要删除吗？"
										@confirm="handleDel(scope.row.id)"
										@cancel="load"
									>
										<template #reference>
											<el-button type="danger" :icon="Delete" size="small"> 删除 </el-button>
										</template>
									</el-popconfirm>
								</div>
							</div>
						</template>
					</el-table-column>
				</el-table>
				<!--      分页按钮-->
				<div class="pagination">
					<el-pagination
						:current-page="pageNum"
						:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
						size="small"
						layout="total, sizes, prev, pager, next, jumper"
						:total="Number(total)"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { CircleCloseFilled, Close, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import router from '@/router'
import UploadImage from '@/components/upload/upload-image/index.vue'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const name = ref('')
const belongFilter = ref('')
const belongSuitFilter = ref('')
const suitOptions = ref([])
const belongSuitOptions = ref([])
const formSize = ref('default')
const ruleFormRef = ref()

const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	aggressivity: 0,
	critical: 0,
	defense: 0,
	mana: 0,
	fire: 0,
	ice: 0,
	drug: 0,
	thunder: 0,
	belong: undefined
})

const belongOptions = ref([
	{ value: 1, label: '兵器' },
	{ value: 2, label: '葫芦' },
	{ value: 3, label: '头冠' },
	{ value: 4, label: '臂甲' },
	{ value: 5, label: '衣甲' },
	{ value: 6, label: '腿甲' },
	{ value: 7, label: '珍玩' },
	{ value: 8, label: '精魄' }
])

const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	aggressivity: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	critical: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	defense: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	mana: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	fire: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	ice: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	drug: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	thunder: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	belong: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

const handleSilentClose = () => {
	handleResetForm(ruleFormRef.value)
	dialogVisible.value = false
}

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}
// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/equip/${id}`)
	Object.assign(form, res.data)

	if (res.data.belongSuit && !suitOptions.value.some(item => item.id === res.data.belongSuit)) {
		const suitRes = await request.get(`/suit/${res.data.belongSuit}`)
		suitOptions.value = [suitRes.data, ...suitOptions.value]
	}
}
const $route = router
const handleUpdate1 = async id => {
	router.push({
		path: '/personality',
		query: {
			id,
			suitOptions: JSON.stringify(suitOptions.value)
		}
	})
}
// 单个删除方法
const handleDel = async id => {
	await request.delete(`/equip/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}
// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/equip/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

const searchSuits = async (query = '') => {
	const res = await request.get('/suit/list', {
		params: { name: query }
	})
	suitOptions.value = res.data
}

const searchBelongSuits = async (query = '') => {
	const res = await request.get('/suit/list', {
		params: { name: query }
	})
	belongSuitOptions.value = res.data
}

const getSuitName = id => {
	const suit = suitOptions.value.find(item => item.id === id)
	return suit ? suit.name : '无'
}

const getBelongLabel = value => {
	const item = belongOptions.value.find(item => item.value === value)
	return item ? item.label : '未知类型'
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/equip/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			belongSuit: belongSuitFilter.value,
			belong: belongFilter.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
}
// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	name.value = ''
	belongSuitFilter.value = ''
	belongFilter.value = ''
	load()
}
// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}
// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/equip/${form.id}` : '/equip',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/equip/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}
// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/equip/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}
// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		aggressivity: 0,
		critical: 0,
		defense: 0,
		mana: 0,
		fire: 0,
		ice: 0,
		drug: 0,
		thunder: 0
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}

onMounted(async () => {
	await searchSuits()
	await searchBelongSuits()
})
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.pagination {
	margin-top: 10px;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.custom-close-btn {
	border: none !important;
	padding: 5px !important;
	transition: all 0.3s;

	&:hover {
		transform: rotate(90deg);
		color: #ff4d4f !important;
		background: rgba(255, 77, 79, 0.1) !important;
	}
}
</style>
